<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  fetchArticleList,
  fetchCategories,
  fetchHotList,
  fetchRecommendAuthors,
  fetchTags,
} from "@/apis/blog";

const loading = ref(false);
const viewMode = ref("list"); // list | grid
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const keyword = ref("");
const sortBy = ref("time"); // time | read | like
const selectedCategories = ref([]);

const articles = ref([]);
const categories = ref([]);
const hotList = ref([]);
const recommendAuthors = ref([]);
const tags = ref([]);

const carouselItems = ref([
  {
    image: "https://img.shetu66.com/2022/08/cutCoverImg/1663066152688406.jpg",
    link: "https://example.com/ad1",
  },
  {
    image: "https://via.placeholder.com/300x150?text=Ad+2",
    link: "https://example.com/ad2",
  },
  {
    image: "https://via.placeholder.com/300x150?text=Ad+3",
    link: "https://example.com/ad3",
  },
]);

async function loadData() {
  loading.value = true;
  try {
    const [listRes, catRes, hotRes, recRes, tagRes] = await Promise.all([
      fetchArticleList({
        page: page.value,
        pageSize: pageSize.value,
        keyword:
          activeQuick?.value !== "全部" ? activeQuick.value : keyword.value,
        sortBy: sortBy.value,
        categories: selectedCategories.value,
      }),
      fetchCategories(),
      fetchHotList(),
      fetchRecommendAuthors(),
      fetchTags(),
    ]);
    articles.value = listRes.data.items;
    total.value = listRes.data.total;
    categories.value = catRes.data;
    hotList.value = hotRes.data;
    recommendAuthors.value = recRes.data;
    tags.value = tagRes.data;
  } catch (e) {
    ElMessage.error("加载失败，请稍后重试");
  } finally {
    loading.value = false;
  }
}

function handleSearch() {
  page.value = 1;
  loadData();
}

// 常用筛选快捷按钮（按标题关键字筛选）
const quickCategoryNames = [
  "全部",
  "Java",
  "人工智能",
  "算法",
  "Python",
  "前端",
  "后端",
  "数据库",
  "C++",
  "Go",
];
const activeQuick = ref("全部");

function isQuickChecked(name) {
  return activeQuick.value === name;
}

function toggleQuick(name) {
  activeQuick.value = name;
  // 点击按钮仅影响筛选，不改动输入框内容
  handleSearch();
}

function handleSortChange(val) {
  sortBy.value = val;
  page.value = 1;
  loadData();
}

function handlePageChange(val) {
  page.value = val;
  loadData();
}

function handlePageSizeChange(val) {
  pageSize.value = val;
  page.value = 1;
  loadData();
}

function handleCarouselClick(link) {
  window.open(link, "_blank");
}

onMounted(loadData);
</script>

<template>
  <el-container class="blog-home blog-theme">
    <el-aside width="260px" class="blog-aside-left">
      <el-carousel
        height="300px"
        indicator-position="outside"
        arrow="always"
        :interval="5000"
        autoplay
        class="carousel-fixed"
      >
        <el-carousel-item
          v-for="(item, index) in carouselItems"
          :key="index"
          @click="handleCarouselClick(item.link)"
        >
          <img :src="item.image" alt="carousel image" class="carousel-image" />
        </el-carousel-item>
      </el-carousel>
    </el-aside>

    <el-main class="blog-main">
      <el-card shadow="never" class="toolbar">
        <div class="toolbar-row">
          <el-input
            v-model="keyword"
            placeholder="搜索文章标题/内容/作者"
            clearable
            @keyup.enter="handleSearch"
            class="search-input"
          />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-radio-group
            v-model="viewMode"
            class="view-switch"
            style="display: none"
          >
            <el-radio-button label="list">列表视图</el-radio-button>
          </el-radio-group>
        </div>
        <div class="quick-cats">
          <el-button
            v-for="name in quickCategoryNames"
            :key="name"
            size="small"
            :type="isQuickChecked(name) ? 'primary' : 'default'"
            :plain="!isQuickChecked(name)"
            @click="toggleQuick(name)"
            >{{ name }}</el-button
          >
        </div>
      </el-card>

      <el-skeleton :loading="loading" animated :rows="8">
        <template #default>
          <div v-if="viewMode === 'list'" class="article-list">
            <el-card
              v-for="a in articles"
              :key="a.id"
              class="article-item"
              shadow="hover"
              @click="$router.push(`/c-oj/home/blog/${a.id}`)"
            >
              <div class="item-title">{{ a.title }}</div>
              <div class="item-meta">
                <span>{{ a.author }}</span> · <span>{{ a.publishTime }}</span> ·
                <span>阅读 {{ a.readCount }}</span> ·
                <span>点赞 {{ a.likeCount }}</span>
              </div>
              <div class="item-summary">{{ a.summary }}</div>
              <div class="item-tags">
                <el-tag
                  v-for="t in a.tags"
                  :key="t"
                  size="small"
                  type="success"
                  >{{ t }}</el-tag
                >
              </div>
            </el-card>
          </div>

          <el-row v-else :gutter="16" class="article-grid">
            <el-col
              v-for="a in articles"
              :key="a.id"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
            >
              <el-card
                class="grid-card"
                shadow="hover"
                @click="$router.push(`/c-oj/home/blog/${a.id}`)"
              >
                <div class="grid-title">{{ a.title }}</div>
                <div class="grid-meta">
                  {{ a.author }} · {{ a.publishTime }}
                </div>
                <div class="grid-summary">{{ a.summary }}</div>
              </el-card>
            </el-col>
          </el-row>
        </template>
      </el-skeleton>

      <div class="pager">
        <el-pagination
          background
          layout="sizes, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="page"
          @update:page-size="handlePageSizeChange"
          @update:current-page="handlePageChange"
        />
      </div>
    </el-main>

    <el-aside width="300px" class="blog-aside-right">
      <el-card shadow="never" class="card">
        <template #header>
          <div class="card-header">热门文章</div>
        </template>
        <div class="hot-list">
          <div
            v-for="(h, idx) in hotList"
            :key="h.id"
            class="hot-item"
            @click="$router.push(`/c-oj/home/blog/${h.id}`)"
          >
            <span class="hot-index">{{ idx + 1 }}</span>
            <span class="hot-title">{{ h.title }}</span>
          </div>
        </div>
      </el-card>

      <el-card shadow="never" class="card">
        <template #header>
          <div class="card-header">推荐作者</div>
        </template>
        <div class="author-list">
          <div v-for="u in recommendAuthors" :key="u.id" class="author-item">
            <el-avatar :size="32" :src="u.avatar" />
            <div class="author-meta">
              <div class="name">{{ u.name }}</div>
              <el-button size="small" type="primary">关注</el-button>
            </div>
          </div>
        </div>
      </el-card>
    </el-aside>
  </el-container>
</template>

<style lang="scss" scoped>
.blog-home {
  max-width: 100%;
  margin: 0 auto;
  margin-top: -60px;
  display: flex;
  align-items: flex-start;
}
.blog-aside-left,
.blog-main,
.blog-aside-right {
  padding-top: 0;
  margin-top: 0;
}
.card {
  margin-bottom: 16px;
}
.card-header {
  font-weight: 600;
  color: var(--text-color);
}
.tag-cloud .el-tag {
  margin: 4px;
}
.toolbar {
  margin-bottom: 16px;
}
.toolbar-row {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}
.search-input {
  flex: 1;
  min-width: 220px;
}
.view-switch {
  margin-left: auto;
}
.sort-select {
  min-width: 160px;
}
.article-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.article-item {
  cursor: pointer;
}
.item-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color);
}
.item-meta {
  color: #7f8c8d;
  margin: 6px 0;
}
.item-summary {
  color: #2c3e50;
}
.item-tags {
  margin-top: 8px;
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}
.article-grid {
  margin-top: 8px;
}
.grid-card {
  cursor: pointer;
}
.grid-title {
  font-weight: 600;
}
.grid-meta {
  color: #7f8c8d;
  margin: 6px 0;
}
.grid-summary {
  color: #2c3e50;
}
.pager {
  display: flex;
  justify-content: flex-end;
  margin: 16px 0;
}

@media (max-width: 1024px) {
  .blog-aside-left {
    display: none;
  }
}
@media (max-width: 768px) {
  .blog-aside-right {
    display: none;
  }
}
</style>
